package com.jillchen.grpc.server.convertprovidors;




import com.aspose.note.*;
import com.jillchen.grpc.server.utils.AbsConverter;
import org.apache.commons.io.FilenameUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.Arrays;

public class ConvertNote extends AbsConverter {

    @Override
    public int Convert(String InFile,String OutFile)  {

        try {

            long old = System.currentTimeMillis();

            Document oneFile = new Document(InFile);
            PdfSaveOptions options = new PdfSaveOptions();
            oneFile.save(OutFile);
            long now = System.currentTimeMillis();
            System.out.println("convert OK! " + ((now - old) / 1000.0) + "s");
            return 0;
        }
        catch (Exception ex)
        {
            System.out.println(ex.getMessage()+"\r\n"+ Arrays.toString(ex.getStackTrace()));
            return  -3;
        }
    }

    @Override
    public int Convert(InputStream inputStream, String InFile, ByteArrayOutputStream outputStream, String OutFile) {

        try {
            String FileExt = FilenameUtils.getExtension(OutFile).toUpperCase();
            long old = System.currentTimeMillis();
            final boolean b1 = "JPG".equals(FileExt) ||"JPEG".equals(FileExt) || "PNG".equals(FileExt) || "BMP".equals(FileExt) || "GIF".equals(FileExt) || "TIFF".equals(FileExt);
            Document oneFile = new Document(inputStream);
            if("PDF".equals(FileExt)) {
                PdfSaveOptions options = new PdfSaveOptions();
                oneFile.save(outputStream,options);
            }else if("HTML".equals(FileExt))
            {
                HtmlSaveOptions options = new HtmlSaveOptions();
                oneFile.save(outputStream,options);

            }else if(b1)
            {
                int f = SaveFormat.Png;
                for (Field e : SaveFormat.class.getDeclaredFields()) {
                    if (e.getName().toUpperCase().equals(FileExt)) {
                        f = e.getInt(SaveFormat.class);
                    }
                }
                ImageSaveOptions options = new ImageSaveOptions(f);
                oneFile.save(outputStream,options);

            }else{
                oneFile.save(outputStream);
            }

            long now = System.currentTimeMillis();
            System.out.println("convert OK! " + ((now - old) / 1000.0) + "s");
            return 0;
        }
        catch (Exception ex)
        {
            System.out.println(ex.getMessage()+"\r\n"+ Arrays.toString(ex.getStackTrace()));
            return  -3;
        }
    }
}
